<template>
    <div class="my-orders-container">
      <el-card class="orders-card">
        <template #header>
          <div class="card-header">
            <span>我的订单</span>
            <el-button type="primary" size="small" @click="fetchOrders">刷新数据</el-button>
          </div>
        </template>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="orderList.length === 0" class="empty-container">
          <el-empty description="暂无订单信息" />
        </div>
        
        <div v-else>
          <el-table
            :data="orderList"
            style="width: 100%"
            border
            stripe
            v-loading="loading"
          >
            <el-table-column label="订单ID" width="80">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="house_name" label="房源名称" min-width="150" show-overflow-tooltip />
            <el-table-column label="租期" width="200">
              <template #default="scope">
                <span>{{ formatDate(scope.row.start_date) }} 至 {{ formatDate(scope.row.end_date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="landlord_name" label="房东" width="100" />
            <el-table-column prop="amount" label="金额(元)" width="120">
              <template #default="scope">
                <span>{{ formatCurrency(scope.row.amount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rent_date" label="支付时间" width="180">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.rent_date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pay_type" label="支付方式" width="120" />
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  
  // 响应式数据
  const loading = ref(true)
  const orderList = ref([])
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  
  // 格式化货币
  const formatCurrency = (value) => {
    if (!value && value !== 0) return '-'
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '未设置'
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
  
  // 格式化日期时间
  const formatDateTime = (dateString) => {
    if (!dateString) return '未设置'
    const date = new Date(dateString)
    return `${formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
  }
  
  // 获取订单列表
  const fetchOrders = async () => {
  loading.value = true
  try {
    // 构建请求参数（如果后端不分页，page和pageSize可以去掉）
    let params = {
      tenant_id: localStorage.getItem('userId')
    }

    const response = await axios.get('http://127.0.0.1:5000/api/rent/rentList', {
      params,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.status === 200) {
      const allData = response.data.data || []

      total.value = allData.length

      // 计算当前页的数据区间
      const start = (currentPage.value - 1) * pageSize.value
      const end = currentPage.value * pageSize.value

      // 取当前页数据做展示
      orderList.value = allData.slice(start, end).map(item => ({
        ...item,
        amount: parseFloat(item.amount)
      }))
    } else {
      ElMessage.error(response.data.msg || '获取订单信息失败')
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

  
  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchOrders()
  }
  
  // 处理每页显示数量变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchOrders()
  }
  
  onMounted(() => {
    fetchOrders()
  })
  
  // 暴露方法给父组件调用
  defineExpose({
    fetchOrders
  })
  </script>
  
  <style scoped>
  .my-orders-container {
    width: 100%;
  }
  
  .orders-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .loading-container, .empty-container {
    padding: 20px;
    text-align: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>